#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mqueue.h>
#include <pthread.h>
#include "mqtt_handler.h"
#include "msg_queue.h"
#include "json_quick_find.h"
#include "cJSON.h"
#include "shm_reader.h"

extern MQTTClient mqttClient;
extern mqd_t msg_queue;
extern int current_mode; // 1=定时上报 2=对比上报 3=查询上报
extern cJSON* baseline_data; // 用于对比上报的基准数据
extern pthread_mutex_t data_mutex; // 保护基准数据
extern pthread_mutex_t mode_mutex;
extern pthread_mutex_t mqtt_mutex;
extern char* shm_ptr;
extern int shm_id;


void mqtt_init(MQTTClient* client, MQTTClient_messageArrived* msgarrvd) {
    MQTTClient_create(client, MQTT_ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    
    if (MQTTClient_connect(*client, &conn_opts) != MQTTCLIENT_SUCCESS) {
        fprintf(stderr, "MQTT connection failed\n");
        exit(EXIT_FAILURE);
    }
    
    // 设置消息到达回调
    MQTTClient_setCallbacks(*client, NULL, NULL, msgarrvd, NULL);

    // 添加连接状态检查
    int rc = MQTTClient_connect(*client, &conn_opts);
    if (rc != MQTTCLIENT_SUCCESS) {
        fprintf(stderr, "MQTT连接失败! 错误码: %d\n", rc);
        if (rc == 1) fprintf(stderr, "错误: 连接被拒绝 - 协议版本错误\n");
        else if (rc == 2) fprintf(stderr, "错误: 连接被拒绝 - 客户端ID无效\n");
        else if (rc == 3) fprintf(stderr, "错误: 连接被拒绝 - 服务器不可用\n");
        else if (rc == 4) fprintf(stderr, "错误: 连接被拒绝 - 用户名或密码错误\n");
        else if (rc == 5) fprintf(stderr, "错误: 连接被拒绝 - 未授权\n");
        else fprintf(stderr, "未知错误\n");
        return;
    }
    printf("MQTT连接成功!\n");
}

void mqtt_publish(MQTTClient client, const char* topic, const char* payload) {
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    pubmsg.payload = (void*)payload;
    pubmsg.payloadlen = (int)strlen(payload);
    pubmsg.qos = 0;
    pubmsg.retained = 0;
    
    
    MQTTClient_deliveryToken token;
    //MQTTClient_publishMessage(client, topic, &pubmsg, &token);
    //MQTTClient_waitForCompletion(client, token, TIMEOUT);
    MQTTClient_publishMessage(client, topic, &pubmsg, &token);
    // 不等待完成，异步发送（需确保payload生命周期足够）
}

void mqtt_subscribe(MQTTClient client, const char* topic) {
    int rc = MQTTClient_subscribe(client, topic, QOS);
    if (rc != MQTTCLIENT_SUCCESS) {
        fprintf(stderr, "订阅主题 %s 失败! 错误码: %d\n", topic, rc);
    } else {
        printf("成功订阅主题: %s\n", topic);
    }
}

// MQTT消息回调
int mqtt_callback(void* context, char* topicName, int topicLen, MQTTClient_message* message) {
    char* payload = (char*)message->payload;
    printf("Received MQTT command: %s\n", payload);
    
    
// 快速查找type字段的值
    char* type_str = "\"type\":";
    int type = -1;
    type = quick_find(payload, type_str);

    // 根据类型处理
    switch (type) {
        case 1:  // 控制命令
            send_to_queue(msg_queue, payload);
            break;
        case 2:  // 切换模式
            printf("Switching operation mode\n");
            // 模式切换逻辑
            char* mode_str = "\"mode\":";
            int mode = -1;
            mode = quick_find(payload, mode_str);
             if (mode >= 1 && mode <= 3) {
                current_mode = mode;
                printf("Current mode set to %d\n", mode);//1.循环;2.对比;3.刷新
                
                // 切换到对比上报模式时，先主动进行一次上报并设置对比基准数据
                if (mode == 2) {
                    pthread_mutex_lock(&mode_mutex);
                    pthread_mutex_lock(&data_mutex);
                    if (baseline_data) {
                        cJSON_Delete(baseline_data);
                        baseline_data = NULL;
                    }
                    
                    // 获取当前共享内存数据并上报
                    //init_shm();
                    char* sensor_data = read_shm_data();
                    
                    if (sensor_data && strlen(sensor_data) > 0) {
                        printf("Initial full report for mode 2: %s\n", sensor_data);
                        safe_mqtt_publish(mqttClient, "sensor/data", sensor_data);
                        
                        // 解析并保存为基准数据
                        baseline_data = cJSON_Parse(sensor_data);
                    }
                    free(sensor_data);
                    pthread_mutex_unlock(&data_mutex);
                    pthread_mutex_unlock(&mode_mutex);
                }
            }
            
            break;
        case 3:  // 刷新命令
            printf("Processing refresh command\n");
            // 刷新逻辑
             if (current_mode == 3) {
                //init_shm();
                const char* sensor_data = read_shm_data_direct();
                
                if (sensor_data && strlen(sensor_data) > 0) {
                    printf("Sending data for refresh command: %s\n", sensor_data);
                    safe_mqtt_publish(mqttClient, "sensor/data", sensor_data);
                }
                //free(sensor_data);
            }
            break;
        default:
            printf("Unknown command type: %d\n", type);
            break;

    }
    
    MQTTClient_freeMessage(&message);
    return 1;
}



void mqtt_cleanup(MQTTClient client) {
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
}

// 封装安全的MQTT发布函数
void safe_mqtt_publish(MQTTClient client, const char* topic, const char* payload) {

    
    pthread_mutex_lock(&mqtt_mutex);
    // 执行原始的MQTT发布操作
    mqtt_publish(client, topic, payload);
    
    pthread_mutex_unlock(&mqtt_mutex);
    

}